package com.qiankan.qmsj.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.qiankan.qmsj.R;
import com.qiankan.qmsj.UserInfo;
import com.qiankan.qmsj.adapter.CommonAdapter;
import com.qiankan.qmsj.db.UserDBHelper;
import com.qiankan.qmsj.entity.Labels;
import com.qiankan.qmsj.entity.Product;
import com.qiankan.qmsj.entity.Result;
import com.qiankan.qmsj.net.APIHub;
import com.qiankan.qmsj.utils.AsyncLoadImage;
import com.qiankan.qmsj.utils.ColorUtils;
import com.qiankan.qmsj.utils.StringUtils;
import com.qiankan.qmsj.viewHolder.ApplyRecordViewHolder;
import com.qiankan.qmsj.viewHolder.CommonViewHolder;
import com.qiankan.qmsj.widget.TipToast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ApplyRecordActivity extends BaseActivity {
    @BindView(R.id.emptyView)
    LinearLayout mEmptyView;
    @BindView(R.id.rv_applyRecord)
    RecyclerView mRvApplyRecord;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    private UserInfo userInfo;
    private CommonAdapter<Product> loanRecordAdapter;
    private List<Product> loanRecordList = new ArrayList<>();// 贷款记录集合

    @Override
    public int getContentViewId() {
        return R.layout.activity_apply_record;
    }

    public static Intent newIntent(Context context) {
        return new Intent(context, ApplyRecordActivity.class);
    }

    @Override
    protected void initAllMembersView(Bundle savedInstanceState) {
        userInfo = UserDBHelper.getInstance(this).getUserInfo();
        if (userInfo == null || TextUtils.isEmpty(userInfo.getId())) {
            Intent intent = LogInActivity.newIntent(this);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();
            return;
        }
        initApplyRecord();
        showLoadingDialog();
        refresh();
    }

    private void initApplyRecord() {
        mRvApplyRecord.setHasFixedSize(true);
        mRvApplyRecord.setLayoutManager(new LinearLayoutManager(this));
        mRvApplyRecord.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        loanRecordList = new ArrayList<>();
        loanRecordAdapter = new CommonAdapter<Product>(this, ApplyRecordViewHolder.class, loanRecordList, R.layout.apply_record_item) {
            @Override
            public void convert(RecyclerView.ViewHolder holder, final Product item, int position) {
                ApplyRecordViewHolder viewHolder = (ApplyRecordViewHolder) holder;
                viewHolder.mProductName.setText(item.getName());
                viewHolder.mProductTitle.setText(item.getName());
                viewHolder.mProduceIntro.setText(item.getIntro());
                viewHolder.mRecordDate.setText(item.getCreatetime());
                AsyncLoadImage.loadImage(item.getIcon(), viewHolder.mProductLogo, R.mipmap.ic_launcher);
                StringUtils.setTVColor("最高金额：" + StringUtils.convertNum(item.getMaxmoney()) + "元 ", '：', '元', getResources().getColor(R.color.dark_yellow), viewHolder.mMaxMoney);
                StringUtils.setTVColor("成功贷款：" + StringUtils.convertNum(item.getApplynum()) + "人 ", '：', '人', getResources().getColor(R.color.black_text), viewHolder.mApplyNum);
                viewHolder.mLabelRoot.removeAllViews();
                for (Labels label : item.getLabels()) {
                    TextView textView = new TextView(ApplyRecordActivity.this);
                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    lp.setMargins(10, 0, 0, 0);
                    textView.setPadding(5, 1, 5, 1);
                    textView.setTextSize(12);
                    textView.setLayoutParams(lp);
                    textView.setText(label.getName());
                    textView.setTextColor(Color.parseColor("#FFFFFF"));
                    try {
                        textView.setBackgroundColor(Color.parseColor(ColorUtils.getHex(label.getColor())));
                    } catch (Exception e) {

                    }
                    viewHolder.mLabelRoot.addView(textView);
                }
                viewHolder.mApplyAgain.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {//重新申请
                        reapply(item.getId());
                        Bundle bundle = new Bundle();
                        bundle.putString("url", item.getLink());
                        startActivity(WebActivity.newIntent(ApplyRecordActivity.this, bundle));
                    }
                });
                viewHolder.mCallPhone.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (!TextUtils.isEmpty(item.getPhone())) {
                            Intent intent = new Intent(Intent.ACTION_DIAL);
                            Uri uri = Uri.parse("tel:" + item.getPhone());
                            intent.setData(uri);
                            startActivity(intent);
                        }
                    }
                });
                viewHolder.setOnRecyclerViewListener(new CommonViewHolder.OnRecyclerViewListener() {
                    @Override
                    public void onItemClick(View view) {//产品详情
                        Intent intent = ProductDetailActivity.newIntent(ApplyRecordActivity.this, item);
                        startActivity(intent);
                    }
                });
            }
        };
        mRvApplyRecord.setAdapter(loanRecordAdapter);
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refresh();
            }
        });
    }

    private void refresh() {
        Map<String, String> param = new HashMap<String, String>();
        param.put("user", userInfo.getId());
        APIHub.getsInstance().getBaseService().loanRecord(param).enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                smartRefreshLayout.finishRefresh();
                dismissLoadingDialog();
                Result result = response.body();
                if (result.getCode().equals("200")) {
                    List<Product> recordList = new Gson().fromJson(result.getData(), new TypeToken<List<Product>>() {
                    }.getType());
                    loanRecordList.clear();
                    loanRecordList.addAll(recordList);
                    if (loanRecordList.size() == 0) {
                        mEmptyView.setVisibility(View.VISIBLE);
                    } else {
                        mEmptyView.setVisibility(View.GONE);
                    }
                    loanRecordAdapter.notifyDataSetChanged();
                } else {
                    TipToast.toast(ApplyRecordActivity.this, result.getRemark());
                }
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                smartRefreshLayout.finishRefresh();
                dismissLoadingDialog();
                TipToast.toast(ApplyRecordActivity.this, "网络连接失败");
            }
        });
    }

    private void reapply(String produceId) {
        showLoadingDialog();
        Map<String, String> param = new HashMap<String, String>();
        param.put("user", userInfo.getId());
        param.put("product", produceId);
        APIHub.getsInstance().getBaseService().reapply(param).enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                dismissLoadingDialog();
                Result result = response.body();
                if (result.getCode().equals("200")) {
                } else {
                    TipToast.toast(ApplyRecordActivity.this, result.getRemark());
                }
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                dismissLoadingDialog();
                TipToast.toast(ApplyRecordActivity.this, "网络连接失败");
            }
        });
    }

    @OnClick(R.id.iv_back)
    public void onClickBack(View view) {
        finish();
    }
}
